#pragma once
#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>
#include "Log.hpp"
#include "InetAddr.hpp"

const std::string DefaultDict = "./Dictionary.txt";
using namespace LogModule;

class Dict
{
public:
    Dict(const std::string path = DefaultDict)
        :_path(path)
    {

    }
    bool DictInit()
    {
        std::ifstream in(_path);
        if(!in.is_open())
        {
           LOG(LogLevel::ERROR) << "# open error";
           return false;
        }
        std::string line;
        while(std::getline(in,line))
        {
            auto pos = line.find(": ");
            if(pos == std::string::npos)
            {
                LOG(LogLevel::INFO) << " 解析 " << line << " 失败 ";
                continue;
            }

            std::string english = line.substr(0,pos);
            std::string chinese = line.substr(pos+2);
            if(english.empty() || chinese.empty())
            {
                LOG(LogLevel::WARRING) << "没有有效内容";
                continue;
            }
            LOG(LogLevel::INFO) << "解析：" << english << ": " << chinese << " 成功";

            _dict.insert(std::make_pair(english,chinese));

        }
        in.close();
        return true;
    }

    std::string Translate(const std::string& word, InetAddr& client)
    {
        auto iter = _dict.find(word);
        if(iter == _dict.end())
        {
            LOG(LogLevel::DEBUG) << client.IP() << client.Port() << "进入到了翻译模块，未查询到当前单词";
            return "NONE";
        }
        LOG(LogLevel::INFO) << client.IP() << client.Port() << "进入到了翻译模块，查询到当前单词 " <<  word << " -> " << iter->second;

        return iter->second;
    }

private:
    std::string _path;
    std::unordered_map<std::string, std::string> _dict;
};